<template>
  <div class="chat-bot">
    <div class="chat-window">
      <div v-for="(message, index) in messages" :key="index" :class="message.sender">
        <p>{{ message.text }}</p>
      </div>
    </div>
    <div class="input-area">
      <input
          type="text"
          v-model="userInput"
          @keyup.enter="sendMessage"
          placeholder="输入消息..."
      />
      <button @click="sendMessage">发送</button>
    </div>
  </div>
</template>

<script>
import axios from "axios";

export default {
  data() {
    return {
      userInput: "",
      messages: [
        { sender: "bot", text: "您好，我是您的健康管家！有什么可以帮你的吗？" },
      ],
    };
  },
  methods: {
    async sendMessage() {
      if (!this.userInput.trim()) return;

      // 添加用户消息到聊天记录
      this.messages.push({ sender: "user", text: this.userInput });

      const userMessage = this.userInput;
      this.userInput = ""; // 清空输入框

      try {
        // 调用聊天机器人 API
        const response = await axios.post("https://api.gpt.ge/v1/chat/completions", {
          model: "gpt-4o", // 使用的模型
          messages: [{ role: "user", content: userMessage }],
        }, {
          headers: {
            "Authorization": `sk-RayjINE2fvQwJMjZ47Ee58Fc092546B4A41236E5BcE3D9De`, // 替换为你的 OpenAI API 密钥
            "Content-Type": "application/json",
          },
        });

        const botReply = response.data.choices[0].message.content;

        // 添加机器人消息到聊天记录
        this.messages.push({ sender: "bot", text: botReply });
      } catch (error) {
        console.error("API 请求失败：", error);
        this.messages.push({ sender: "bot", text: "抱歉，我无法处理你的请求。" });
      }
    },
  },
};
</script>

<style scoped>
/* 容器样式，使聊天机器人居中 */
.chat-bot-container {
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
  height: 100vh; /* 设置容器高度为视口高度 */
  background-color: #f5f5f5; /* 背景颜色可以根据需求调整 */
}

/* 聊天机器人样式 */
.chat-bot {
  margin: 0 auto;
  width: 800px; /* 设置宽度 */
  height: 800px; /* 设置高度 */
  border: 1px solid #ccc;
  border-radius: 8px;
  padding: 16px;
  display: flex;
  flex-direction: column;
  background-color: #fff; /* 白色背景 */
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2); /* 添加阴影效果 */
}

.chat-window {
   flex: 1;
   overflow-y: auto;
   margin-bottom: 16px;
   border: 1px solid #ddd;
   border-radius: 8px;
   padding: 8px;
 }

.chat-window .bot {
  text-align: left;
  color: #333;
}

.chat-window .user {
  text-align: right;
  color: #007BFF;
}

.input-area {
  display: flex;
  gap: 8px;
}

input {
  flex: 1;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

button {
  padding: 8px 16px;
  border: none;
  background-color: #007BFF;
  color: white;
  border-radius: 4px;
  cursor: pointer;
}

button:hover {
  background-color: #0056b3;
}
</style>